<?php

/**
 * Util-模型
 */
class Util {

    /**
     * 获取系列化哈希
     * @param type $obj
     * @return type
     */
    public static function getSerializeHash($obj) {
        return hash('md4', serialize($obj));
    }

    /**
     * 获取密钥
     * @param type $serial
     * @return boolean
     */
    public static function getAesKey($serial) {
        $secret = include dirname(__FILE__) . '/../config/appkeys.php';
        $serialStr = array('abd', 'pos', 'zqm');
        foreach ($serialStr as $index => $str) {
            if (strpos($serial, $str) !== -1) {
                return $secret[$index];
            }
        }
        return false;
    }

    /**
     * 获取密钥组
     * @return type
     */
    public static function getAesSecretSerial() {
        $redis = mRedis::get_instance();
        $serials = $redis->hGetAll('util:getAesSecretSerial');
        $redis->del('util:getAesSecretSerial');
        if (!$serials) {
            $serials = include dirname(__FILE__) . '/../config/appkeys.php';
            $redis->hMset('util:getAesSecretSerial', $serials);
        }
        return $serials;
    }

    /**
     * Logger to file
     * @param type $message
     * @param type $type
     */
    public static function log($message) {
        $logDir = APP_PATH . 'app/logs/' . date('Y-m') . '/';
        if (!is_dir($logDir)) {
            mkdir($logDir, 0755);
        }
        if (!is_writable($logDir)) {
            chmod($logDir, 0755);
        }
        error_log(date('Y-m-d H:i:s') . ': ' . $message . PHP_EOL, 3, $logDir . date('Y-m-d') . '.txt');
    }

    /**
     * unicode转化
     * @param type $name
     * @return string
     */
    public static function utf8_unicode($name) {
        $name = iconv('UTF-8', 'UCS-2', $name);
        $len = strlen($name);
        $str = '';
        for ($i = 0; $i < $len - 1; $i = $i + 2) {
            $c = $name[$i];
            $c2 = $name[$i + 1];
            if (ord($c) > 0) {   //两个字节的文字  
                $str .= '\u' . base_convert(ord($c), 10, 16) . str_pad(base_convert(ord($c2), 10, 16), 2, 0, STR_PAD_LEFT);
                //$str .= base_convert(ord($c), 10, 16).str_pad(base_convert(ord($c2), 10, 16), 2, 0, STR_PAD_LEFT);  
            } else {
                $str .= '\u' . str_pad(base_convert(ord($c2), 10, 16), 4, 0, STR_PAD_LEFT);
                //$str .= str_pad(base_convert(ord($c2), 10, 16), 4, 0, STR_PAD_LEFT);  
            }
        }
        #$str = strtoupper($str); //转换为大写  
        return $str;
    }

    /**
     * unicode 转 utf-8
     * @param string $name
     * @return string
     */
    public static function unicode_decode($name) {
        if (empty($name)) {
            return null;
        }
        $name = strtolower($name);
        // 转换编码，将Unicode编码转换成可以浏览的utf-8编码  
        $pattern = '/([\w]+)|(\\\u([\w]{4}))/i';
        preg_match_all($pattern, $name, $matches);
        if (!empty($matches)) {
            $name = '';
            for ($j = 0; $j < count($matches[0]); $j++) {
                $str = $matches[0][$j];
                if (strpos($str, '\\u') === 0) {
                    $code = base_convert(substr($str, 2, 2), 16, 10);
                    $code2 = base_convert(substr($str, 4), 16, 10);
                    $c = chr($code) . chr($code2);
                    $c = iconv('UCS-2', 'UTF-8', $c);
                    $name .= $c;
                } else {
                    $name .= $str;
                }
            }
        }
        return $name;
    }

    /**
     * 获取数据库读写连接
     * @global type $config
     * @return \Phalcon\Db\Adapter\Pdo\Mysql
     */
    public static function getDbConnection() {
        global $config;
        $connection = new \Phalcon\Db\Adapter\Pdo\Mysql(array(
            "host" => $config->database->host,
            "username" => $config->database->username,
            "password" => $config->database->password,
            "dbname" => $config->database->name,
            'charset' => 'utf8',
            'options' => array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8;")
        ));
        return $connection;
    }

    /**
     * 转换用户OSS头像
     * @param int $FUID
     * @param string $FIMGTHUMB
     */
    public static function convUserHead($FUID, $FIMGTHUMB) {
        global $config;
        return empty($FIMGTHUMB) ? '/images/icon/user-head-default.png' : $config->base->ossroot . 'U/' . substr($FUID, 0, 3) . '/others/' . $FUID . '/' . $FIMGTHUMB;
    }

    /**
     * 类微博日期格式化
     * @param UNIXTIME $timestamp
     * @return string
     */
    public static function dateTimeFormat($timestamp) {
        $curTime = time();
        $space = $curTime - $timestamp;
        //1分钟
        if ($space < 60) {
            $string = "刚刚";
            return $string;
        } elseif ($space < 3600) { //一小时前
            $string = floor($space / 60) . "分钟前";
            return $string;
        }
        $curtimeArray = getdate($curTime);
        $timeArray = getDate($timestamp);
        if ($curtimeArray['year'] == $timeArray['year']) {
            if ($curtimeArray['yday'] == $timeArray['yday']) {
                $format = "%H:%M";
                $string = strftime($format, $timestamp);
                return "今天 {$string}";
            } elseif (($curtimeArray['yday'] - 1) == $timeArray['yday']) {
                $format = "%H:%M";
                $string = strftime($format, $timestamp);
                return "昨天 {$string}";
            } else {
                $string = sprintf("%d月%d日 %02d:%02d", $timeArray['mon'], $timeArray['mday'], $timeArray['hours'], $timeArray['minutes']);
                return $string;
            }
        }
        $string = sprintf("%d-%d-%d", $timeArray['year'], $timeArray['mon'], $timeArray['mday'], $timeArray['hours'], $timeArray['minutes']);
        return $string;
    }

    /**
     * 输出Json纠正数字类型
     * @param type $array
     */
    public static function digitFix($array) {
        $ffields = [
            'product_id',
            'order_id',
            'id',
            'aid',
            'uid',
            'sex',
            'client_sex',
            'client_credit',
            'order',
            'isdefault',
            'client_id'
        ];
        foreach ($array as $key => &$a) {
            if (is_array($a)) {
                foreach ($a as $key => &$field) {
                    if (!in_array($key, $ffields)) {
                        continue;
                    }
                    if (is_numeric($field)) {
                        $floatVal = floatval($field);
                        if ($floatVal == $field) {
                            $field = $floatVal;
                        } else {
                            $field = intval($field);
                        }
                    }
                }
            } else {
                if (!in_array($key, $ffields)) {
                    continue;
                }
                if (is_numeric($a) && $key != 'serial_number') {
                    $floatVal = floatval($a);
                    if ($floatVal == $a) {
                        $a = $floatVal;
                    } else {
                        $a = intval($field);
                    }
                }
            }
        }
        return $array;
    }

    /**
     * 获取订单详情中的商品列表
     * @param type $order_details
     * @return type
     */
    public static function getOrderProducts($order_details) {
        global $config;
        foreach ($order_details as $key => &$value) {
            $product = Product::findFirst([
                "product_id = {$value['product_id']}",
                "columns" => "product_name,catimg AS product_image"
            ]);
            if ($product) {
                $product->product_image = $config->base->domainbase . 'uploads/product_hpic/' . $product->product_image;
                $value['product_name'] = $product->product_name;
                $value['product_image'] = $product->product_image;
            } else {
                $value['product_name'] = '';
                $value['product_image'] = '';
            }
        }
        return $order_details;
    }

    /**
     * getIPaddress
     * @return type
     */
    public static function getIp() {
        $cIP = getenv('REMOTE_ADDR');
        $cIP1 = getenv('HTTP_X_FORWARDED_FOR');
        $cIP2 = getenv('HTTP_CLIENT_IP');
        $cIP1 ? $cIP = $cIP1 : null;
        $cIP2 ? $cIP = $cIP2 : null;
        return $cIP;
    }

}
